//
//  TravelsVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/7/21.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "TravelsVC.h"
#import "TCustomCell.h"
#import "TravelsDetailVC.h"
#import "TravelsSearchVC.h"
@interface TravelsVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@end

@implementation TravelsVC
{
    UICollectionView *_collectionView;
    UITextField *_searchBarTraTf;
    NSString *_titleStr;
    CGSize _titleStrSize;
    NSString *_contentStr;
    CGSize _contentStrSize;
    
    //请求下来的字典
    NSDictionary *_responseDic;
    //请求下来的数组
    NSMutableArray *_responseArr;
    NSInteger _currentPage;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSearchTraBar];
    _responseArr = [NSMutableArray array];
    _currentPage = 1;
    [self requestForTravels:_currentPage isFirst:YES];
    [self initCollectionView];
    
    self.navigationItem.backBarButtonItem= [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
}
//导航栏添加搜索框
- (void)addSearchTraBar{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0,  0, KScreenWidth, 30)];
    _searchBarTraTf = [[UITextField alloc]initWithFrame:CGRectMake(20, 0, KScreenWidth-60, 30)];
    _searchBarTraTf.placeholder = @"  搜索游记";
    _searchBarTraTf.tintColor = [UIColor blackColor];
    _searchBarTraTf.font = [UIFont systemFontOfSize:14];
    _searchBarTraTf.backgroundColor = blackLineColore;
    _searchBarTraTf.layer.borderWidth = 1;
    _searchBarTraTf.layer.borderColor = [UIColor grayColor].CGColor;
    _searchBarTraTf.layer.cornerRadius = 8;
    
    UIButton *searchBtn =[[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth-100, 3, 35, 24)];
    searchBtn.backgroundColor = White_Color;
    searchBtn.layer.cornerRadius = 5;
    [searchBtn setImage:[UIImage imageNamed:@"组-3"] forState:UIControlStateNormal];
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [searchBtn addTarget:self action:@selector(searchTraAction) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:_searchBarTraTf];
    [_searchBarTraTf addSubview:searchBtn];
    
    self.navigationItem.titleView = bgView;
}
#pragma - mark RequestForTravels
- (void)requestForTravels:(NSInteger)currentPage isFirst:(BOOL)isFirst{
    //参数
    NSDictionary *parameters = @{
                                 @"pageNum": @(currentPage),
                                 @"pageSize":@"10",
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/travel/list.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        [_collectionView.mj_header endRefreshing];
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSArray *temp = _responseDic[@"list"];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            if (isFirst) {
                if (temp.count == 0) {
                    [SVProgressHUD showImage:nil status:@"暂无数据"];
                }
                [_responseArr removeAllObjects];
            }
            [_responseArr addObjectsFromArray:temp];
            
            if (temp.count < 10) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                [_collectionView.mj_footer endRefreshing];
            }
            
            //请求成功
            [SVProgressHUD showSuccessWithStatus:@"请求游记列表成功"];
            [_collectionView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求游记列表失败"];
    }];
}
//下拉刷新
- (void)refreshDown{
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self requestForTravels:_currentPage isFirst:YES];
    }];
}
//上提加载更多
- (void)refreshLoadMore{
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage++;
        [self requestForTravels:_currentPage isFirst:NO];
    }];
}
//创建一个CollectionView
- (void)initCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置整个collectionView的内边距
    CGFloat paddingY = 10;
    CGFloat paddingX = 10;
    layout.sectionInset = UIEdgeInsetsMake(paddingY, paddingX, paddingY, paddingX);
    //设置每个格子的尺寸
//    layout.itemSize = CGSizeMake(KScreenWidth/2 - 20, 130);
    //设置对齐方式
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight ) collectionViewLayout:layout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"];
    
    [self refreshDown];
    [self refreshLoadMore];
}
#pragma mark -- UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _responseArr.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIDa = @"MyCollectionViewCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIDa forIndexPath:indexPath];
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = superBackgroundColor.CGColor;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(1, 1, KScreenWidth/2 - 20 - 2, 100 - 2)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    NSString *urlStr = _responseArr[indexPath.row][@"thumbs"];
    if (urlStr.length == 2) {
        imageView.image = [UIImage imageNamed:@"picture_10"];
    }else{
        urlStr = [urlStr substringFromIndex:1];
        urlStr = [urlStr substringToIndex:83];
        [imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"picture_8"]];
    }
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    [cell.contentView addSubview:imageView];
    NSString *titleNameStr = _responseArr[indexPath.row][@"title"];
    CGSize titleNameStrSize = [BAAutoSizeWithWH BA_AutoSizeOfHeghtWithText:titleNameStr font:[UIFont systemFontOfSize:13] width:(KScreenWidth/2 - 20)];
    UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, KScreenWidth/2 - 20, titleNameStrSize.height)];
//    titleName.backgroundColor = Red_Color;
    titleName.text = titleNameStr;
    titleName.numberOfLines = 0;
    titleName.textColor = Theme_Color;
    titleName.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:titleName];
    
    UIImageView *iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(1, 100 + titleNameStrSize.height, 25, 25)];
    iconImageView.layer.masksToBounds = YES;
    iconImageView.layer.cornerRadius = 12.5;
    NSString *iconStr = _responseArr[indexPath.row][@"userPhoto"];
    [iconImageView sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"headportrait_1"]];
    [cell.contentView addSubview:iconImageView];
    
    UILabel *authorLb = [[UILabel alloc]initWithFrame:CGRectMake(30, 100 + titleNameStrSize.height, 70, 25)];
    authorLb.text = @"Young";
    authorLb.textColor = Theme_Color;
    authorLb.font = [UIFont systemFontOfSize:12];
    [cell.contentView addSubview:authorLb];
    
//    UIImageView *likeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 60, 100 + 10 + titleNameStrSize.height, 12, 10.5)];
//    likeImageView.image = [UIImage imageNamed:@"favorate_icon"];
//    [cell.contentView addSubview:likeImageView];
    
//    UILabel *likeNumLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 40, 106+titleNameStrSize.height, 35, 15)];
//    likeNumLb.text = @"1111";
//    likeNumLb.textColor = Gray_Color;
//    likeNumLb.font = [UIFont systemFontOfSize:10];
//    [cell.contentView addSubview:likeNumLb];
    
    UILabel *contentLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 100+25+titleNameStrSize.height, KScreenWidth/2 - 20, _contentStrSize.height)];
//    contentLb.backgroundColor = Gray_Color;
    contentLb.text = _contentStr;
    contentLb.numberOfLines = 0;
    contentLb.textColor = [UIColor grayColor];
    contentLb.font = [UIFont systemFontOfSize:11];
    [cell.contentView addSubview:contentLb];
    
//    UIImageView *seeNumImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 120, 125+titleNameStrSize.height+_contentStrSize.height + 15, 13, 8)];
//    seeNumImageView.image = [UIImage imageNamed:@"review_icon"];
//    [cell.contentView addSubview:seeNumImageView];
    
//    UILabel *seeNumLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 100, 127+titleNameStrSize.height+_contentStrSize.height + 10, 35, 15)];
//    seeNumLb.text = @"2222";
//    seeNumLb.textColor = Theme_Color;
//    seeNumLb.font = [UIFont systemFontOfSize:10];
//    [cell.contentView addSubview:seeNumLb];
//    
    UIImageView *commentNumImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 60, 100 + 10 + titleNameStrSize.height, 13, 11.5)];
    commentNumImageView.image = [UIImage imageNamed:@"comment_icon"];
    [cell.contentView addSubview:commentNumImageView];
    
    UILabel *commentNumLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 40, 108+titleNameStrSize.height, 35, 15)];
    commentNumLb.text = @"3333";
    commentNumLb.textColor = Theme_Color;
    commentNumLb.font = [UIFont systemFontOfSize:10];
    [cell.contentView addSubview:commentNumLb];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    _titleStr = _responseArr[indexPath.row][@"title"];
//    _titleStr = @"泸沽湖";
    _titleStrSize = [BAAutoSizeWithWH BA_AutoSizeOfHeghtWithText:_titleStr font:[UIFont systemFontOfSize:13] width:(KScreenWidth/2 - 20)];
    _contentStr = @"游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记内容游记";
    _contentStrSize = [BAAutoSizeWithWH BA_AutoSizeOfHeghtWithText:_contentStr font:[UIFont systemFontOfSize:11] width:(KScreenWidth/2 - 20)];
    return CGSizeMake(KScreenWidth/2 - 20, 100 +25 +_titleStrSize.height +_contentStrSize.height + 5);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return (KScreenWidth - 2*(KScreenWidth/2 - 20))/2;
}
//cell点击时调用
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    TravelsDetailVC *vc = [[TravelsDetailVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.htmlUrlStr = _responseArr[indexPath.row][@"htmlUrl"];
    vc.travelsId = _responseArr[indexPath.row][@"id"];
    vc.travelsName = _responseArr[indexPath.row][@"title"];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)searchTraAction{
    [_searchBarTraTf endEditing:YES];
    TravelsSearchVC *vc = [[TravelsSearchVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.searchKey = _searchBarTraTf.text;
    _searchBarTraTf.text = nil;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
